var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js');
// connection.connect()

// 验证注册手机号是否存在
router.post('/registered', function(req, res, next) {
	// 前端传值
	let params = {
		phone: req.body.phone,
	}
	connection.query("select * from user where phone = '" + params.phone + "'", function(error, results,
		fields) {
		if (results.length > 0) {
			res.send({
				data: {
					success: false,
					msg: '手机号存在',
				}
			})
		} else {
			res.send({
				data: {
					success: true,
				}
			})
		}
	})
});

//TODO 发送验证码
router.post('/code', function(req, res, next) {
	// 前端传值
	let params = {
		phone: req.body.phone,
	}
	// 接入短信SDK


	// 写死验证码
	res.send({
		data: {
			success: true,
			code: 123
		}
	})


});


//注册===>增加一条数据
router.post('/addUser', function(req, res, next) {
	//前端给后端的数据
	let params = {
		phone: req.body.phone,
		userCode: req.body.code
	};
	// ---生成token---
	const jwt = require('jsonwebtoken');
	let payload = {
		name: params.phone
	}; //手机号
	let secret = 'chenkunzhen'; //口令
	let token = jwt.sign(payload, secret);
	// ---生成token---

	if (params.userCode == '123') {
		connection.query(
			`insert into user (userName,userPwd,phone,imgUrl,nickName,token,provider,openid) values ('','123456',${params.phone},'../../static/logo.png','默认昵称','${token}','','')`,
			function(error, results, fields) {
				if (error) throw error
				res.send({
					data: {
						success: true,
						msg: "注册成功"
					}
				})
			})
	}
});

//登录
router.post('/login', function(req, res, next) {
	// 前端传值
	let params = {
		userName: req.body.userName,
		userPwd: req.body.userPwd,
	}
	// 查询用户名或手机号是否存在
	connection.query(`select * from user where userName = ${params.userName} or phone = ${params.userName}`,
		function(error, results, fields) {
			if (error) throw error
			if (results?.length > 0) {
				connection.query("select * from user where userName = '" + params.userName +
					"' or phone = '" + params.userName + "' and userPwd = '" + params.userPwd + "' ",
					function(err, result) {
						if (err) throw err
						if (result.length > 0) {
							res.send({
								code: "200",
								data: {
									success: true,
									msg: '登录成功',
									data: result[0]
								}
							})
						} else {
							res.send({
								code: "400",
								data: {
									success: false,
									msg: '密码不正确'
								}
							})
						}
					})
			} else {
				res.send({
					code: "400",
					data: {
						success: false,
						msg: '用户名或手机号不存在'
					}
				})
			}
		})
});

//其他方式登录
router.post('/loginOther', function(req, res, next) {
	//前端给后端的数据
	let params = {
		provider: req.body.provider, //登录方式
		openid: req.body.openid.slice(0, 8),
		nickName: req.body.nickName,
		avatarUrl: req.body.avatarUrl
	};
	// ---生成token---
	const jwt = require('jsonwebtoken');
	let payload = {
		name: params.phone
	}; //手机号
	let secret = 'chenkunzhen'; //口令
	let token = jwt.sign(payload, secret);
	// ---生成token---

	// 查询数据库中是否有此用户
	connection.query(`select * from user where provider = "${params.provider}" or openid = "${params.openid}"`,
		function(error, results, fields) {
			if (error) throw error
			// 数据存在，读取
			if (results.length > 0) {
				connection.query(
					`select * from user where provider= "${params.provider}" or openid= "${params.openid}"`,
					function(er, ress, field) {
						if (er) throw er
						res.send({
							data: {
								success: true,
								msg: "登录成功",
								data: ress[0]
							}
						})
					})
			} else {
				// 数据不存在，存储信息=》读取
				connection.query(
					`insert into user (userName,userPwd,phone,imgUrl,nickName,token,provider,openid) values ('','123456','${params.openid}','${params.avatarUrl}','${params.nickName}','${token}','${params.provider}','${params.openid}')`,
					function(err, result, field) {
						if (err) throw err
						connection.query(
							`select * from user where provider= "${params.provider}" or openid= "${params.openid}"`,
							function(er, ress, field) {
								if (er) throw er
								res.send({
									data: {
										success: true,
										msg: "登录成功",
										data: ress[0]
									}
								})
							})
					}
				)
			}
		})
})


// 修改信息
router.post('/updateUser', function(req, res, next) {
	console.log(req.body, 'req.body');
	let name = req.body.name
	let phone = req.body.phone
	let sex = req.body.sex
	let date = req.body.date
	let region = JSON.parse(req.body.region)
	let imgUrl = req.body.imgUrl
	// 根据电话查找当前用户
	connection.query(`select * from user where phone = "${phone}"`, function(error, results) {
		if (error) throw error
		let userId = results[0].id //当前用户id
		connection.query(
			`update user set userName= '${name}', phone= '${phone}' , birth_date= '${date}', sex= '${sex}', region= '${region.province},${region.city},${region.district}', imgUrl= '${imgUrl}' where id= ${userId}`,
			function(error, result) {
				if (error) throw error
				res.send({
					data: {
						success: true,
						msg: '修改成功'
					}
				})
			})
	})
})

module.exports = router;